<template>
  <div class="ui-panle">
    <game-item v-model="statusToobloxShow"></game-item>
    <div class="ui-box">
      <div class="server-list" v-loading="serverIsLoading">
        <div style="font-size:14px;padding:5px;color:#ccc">
          我的服务器
        </div>
        <div class="list">
          <div class="item text-ellipsis" :class="{'active':serverListIndex==index,'disable':item.status==0}" v-for="item,index in serverListData"
            @click="()=>{if(item.status!=0){serverChange(item,index)}}" :key="index">
            <div id="icon" :style="{color:item.status==0?'':item.status==-1?'#f73535':'#2fdab2'}"><i class="el-icon-s-platform"></i></div>
            <div id="title">
              <div id="tabs">
                <span class="text-ellipsis">{{item.configinfo.server_hostname}}</span>

                <div id="btn">
                  <div v-if="item.status==0" style="color:#fff;border-radius:100px;background:#999;padding:0 10px;font-size:10px;">
                    未开机
                  </div>
                  <div v-else-if="item.status==-1" style="color:#fff;border-radius:100px;background:#f73535;padding:0 10px;font-size:10px;">
                    服务器未响应
                  </div>
                  <div v-else style="color:#fff;border-radius:100px;background:#2fdab2;padding:0 10px;font-size:10px;">已开机</div>
                  <i class="el-icon-info" style="font-size:18px;flex:1"></i>
                  <!-- <el-button size="mini" type="primary" plain @click="rconConnect(item)">信息</el-button> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="ui-content-view">
        <el-tabs v-model="tabActiveIndex" @tab-click="()=>{}" style="height:100%">
          <el-tab-pane :label="`玩家列表（${playerListData.length}）`" name="0" style="height:100%">
            <div class="player-table">
              <el-table :data="playerListData" ref="playerTable" height="100%" style="width:100%;user-select:text" empty-text="暂无玩家在线或没有选择服务器" v-loading="isLoading">
                <el-table-column prop="SteamID" label="SteamID" width="180" align="center">
                </el-table-column>
                <el-table-column prop="DisplayName" label="昵称" width="180" align="center">
                  <template slot-scope="scope">
                    <el-tag>{{scope.row.DisplayName}}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="Health" label="生命值" width="180" align="center">
                  <template slot-scope="scope">
                    <!-- {{parseInt(scope.row.Health)}} -->
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="parseInt(scope.row.Health)"></el-progress>
                  </template>
                </el-table-column>
                <el-table-column prop="ConnectedSeconds" label="在线时长" width="100" align="center">
                  <template slot-scope="scope">
                    <el-tag type="warning">{{toTime(Number(scope.row.ConnectedSeconds))}}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="Address" label="IP(地区)" width="180" align="center">
                  <template slot-scope="scope">
                    <div style="font-size:12px;color:#888" class="user-select">
                      {{scope.row.Address.split(':')[0]}}<br>
                      <!-- ({{scope.row.areaName.join(' ')}}) -->
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="Ping" label="ping(延迟)" width="100" align="center">
                  <template slot-scope="scope">
                    <el-tag>{{scope.row.Ping}} ms</el-tag>
                    <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete</el-button> -->
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="280">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="statusToobloxShow=true">发送物品</el-button>
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">踢人</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">封禁</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- <div style="padding:10px;">
              <el-row>
                <el-button size="small">默认按钮</el-button>
                <el-button size="small" type="primary">主要按钮</el-button>
                <el-button size="small" type="success">成功按钮</el-button>
                <el-button size="small" type="info">信息按钮</el-button>
                <el-button size="small" type="warning">警告按钮</el-button>
                <el-button size="small" type="danger">危险按钮</el-button>
              </el-row>
            </div> -->
          </el-tab-pane>
          <el-tab-pane label="控制台" name="1">
            <console-panle :lineData="consoleLineData"></console-panle>
            <div class="console-tooblox">
              <el-input type="textarea" :rows="2" placeholder="请输入指令" v-model="msgtextarea">
              </el-input>
              <div style="text-align:right"><el-button type="primary" @click="rcon.command(msgtextarea)">发送指令</el-button></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="权限控制" name="2">
            <div class="access-manage">
              权限控制
            </div>
          </el-tab-pane>
          <el-tab-pane label="配置" name="3">

          </el-tab-pane>
          <el-tab-pane label="关于" name="4">
            <p>御龙 RUST 服主管理系统</p>
            <p>@ Neeco</p>
          </el-tab-pane>
        </el-tabs>
      </div>

    </div>

  </div>
</template>

<script>
import Rcon from '@/libs/rcon'
export default {
  data() {
    return {
      consoleLineData: [],
      statusToobloxShow: false,
      msgtextarea: '',
      serverListIndex: -1,
      serverListData: [],
      playerListData: [],
      tabActiveIndex: '0',
      serverIsLoading: false,
      isLoading: false,
      rcon: null,
      rconConfig: {
        ip: "202.189.8.177",
        port: 21132,
        password: "qinge2000923"
      }
    }
  },
  mounted: function () {
    this.getUserServer()
    // window.onresize=()=>{
    //   console.warn('调整布局')
    //   this.$refs.playerTable.doLayout()
    // }

  },
  methods: {
    IPIPInfo(ip) {
      try {
        return getIPInfo(ip)
      } catch (error) {
        return {}
      }
    },
    serverChange(data, index) {
      this.rconConnect(data)
      this.serverListIndex = index
    },
    rconConnect(config) {
      this.isLoading = true
      let gameconfig = config.configinfo
      console.warn(config)
      if (this.rcon != null) {
        this.rcon.disconnect()
      }
      let rcon = new Rcon(this.rconConfig.ip, gameconfig.rcon_port, gameconfig.rcon_password)
      this.rcon = rcon
      rcon.connect().then(async (res) => {
        console.log(res)
        rcon.send('serverinfo').then((res) => { console.warn(res) })
        rcon.send('playerlist').then((res) => {
          this.playerListData = JSON.parse(res.Message).map((ele) => {
            // console.log(ele.Address)
            let ipInfo = this.IPIPInfo(ele.Address.split(':')[0])
            ele.areaName = [ipInfo.countryName, ipInfo.regionName, ipInfo.cityName]
            return ele
          })
          console.warn(this.playerListData)
          this.isLoading = false
        })
        setInterval(() => {
          rcon.send('serverinfo').then((res) => { console.warn(res) })
          rcon.send('playerlist').then((res) => {
            this.playerListData = JSON.parse(res.Message).map((ele) => {
              // console.log(ele.Address)
              let ipInfo = this.IPIPInfo(ele.Address.split(':')[0])
              ele.areaName = [ipInfo.countryName, ipInfo.regionName, ipInfo.cityName]
              return ele
            })
            console.warn(this.playerListData)
          })
        }, 5000);
        rcon.$on("Chat", (data) => {
          let msgInfo = JSON.parse(data.Message)
          this.$notify({
            title: msgInfo.Username,
            message: msgInfo.Message,
            iconClass: 'el-icon-chat-dot-square',
            duration: 8000,
          });
        })
        rcon.$on("Generic", (data) => {
          let msgInfo = data.Message
          msgInfo=msgInfo.replace(/\n/g,'<br>')
          if (data.Identifier < 2000) {
            this.consoleLineData.push(msgInfo)
          }
        })
        // console.log("异步测试")
        // console.log(await rcon.send('players'))
        // console.log("同步A----------")
        // console.log(await rcon.send('stats'))
        // console.log("同步B----------")
        // console.log(await rcon.send('serverinfo'))
        // console.log("同步C----------")
        // rcon.send('playerlist').then((res) => {
        //   console.warn(JSON.parse(res.Message))
        // })
      }).catch((e) => {
        config.status = -1
        console.warn(config)
      })
    },
    async getUserServer() {
      this.serverIsLoading = true
      this.serverListData = await this.$API.getserver()
      this.serverIsLoading = false
    },
    getPlayerList() {

    },
    toTime(value) {
      if (value <= 0) {
        value = 0
      }
      let theTime = value;//秒
      let middle = 0;//分
      let hour = 0;//小时
      if (theTime > 59) {
        middle = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
      }
      if (middle > 59) {
        hour = parseInt(middle / 60);
        middle = parseInt(middle % 60);
      }
      theTime < 10 ? theTime = '0' + theTime : theTime = theTime
      middle < 10 ? middle = '0' + middle : middle = middle
      hour < 10 ? hour = '0' + hour : hour = hour
      return hour + ':' + middle + ':' + theTime
    }
  },
  components: {

  }
}
</script>
<style lang="less" scoped>
/deep/ .el-tabs__content {
  height: calc(100% - 55px);
}
/deep/ table {
  width: auto !important;
}
.console-tooblox{
  padding:10px 0;
  line-height: 50px;
}
.player-table {
  // overflow: hidden;
  width: 100%;
  overflow: auto;
  height: 100%;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
.ui-panle {
  height: 100%;
}

.ui-box {
  height: 100%;
  display: flex;
  .server-list {
    width: 200px;
    padding: 0 10px;
    height: 100%;
    margin-right: 5px;
    // background:rgba(255,255,255,.3);
    .list {
      .item {
        font-size: 12px;
        position: relative;
        // background: fade(#2fdab2, 10%);
        border: solid 1px transparent;
        background: rgba(0, 0, 0, 0.04);
        border-radius: 6px;
        margin: 5px 0;
        cursor: pointer;
        padding: 5px;
        display: flex;
        // justify-content: center;
        align-items: center;
        &.active {
          background: fade(#2fdab2, 20%);
          border: solid 1px fade(#2fdab2, 70%);
          #icon {
            color: fade(#2fdab2, 70%);
          }
        }
        &.disable {
          cursor: not-allowed;
          // cursor:no-drop;
          // pointer-events: none;
          color: #ddd;
          background: #f1f1f1;
          border: solid 1px #f1f1f1;
          #icon {
            color: #e1e1e1;
          }
        }
        #icon {
          width: 50px;
          text-align: center;
          color: #ccc;
          font-size: 3em;
        }
        #title {
          display: flex;
          flex: 1;
          #tabs {
            display: flex;
            flex-direction: column;
            line-height: 25px;
            span {
              width: 130px;
            }
            #btn {
              display: flex;
              align-items: center;
              // cursor: pointer;
              padding: 0 10px;
              text-align: right;
            }
          }
        }

        // border-bottom: solid 1px rgba(0, 0, 0, 0.1);
      }
    }
    // width: 200px;
  }
  .ui-content-view {
    flex: 1;
  }
}
</style>
